//
//  MyPinDanDetailViewController.m
//  jingjing2.0
//
//  Created by apple on 16/5/18.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "MyPinDanDetailViewController.h"
#import "MyPinDanDetailSection3Cell.h"
#import "DetailPinDanCell.h"
#import "MyPinDanDetailData.h"
#import "ShareData.h"

@interface MyPinDanDetailViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UIButton *_bottomBtn;
    UIView *_bgView;
    UIView *_shareView;
    NSTimer *_DrawTimer;
    enum WXScene _scene;
}
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)MyPinDanDetailData *data;
@property(nonatomic,strong)ShareData *shareData;
@end

@implementation MyPinDanDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"净净拼单";
    UIBarButtonItem *right=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"invite_friend"] style:UIBarButtonItemStylePlain target:self action:@selector(shareFriend)];
    self.navigationItem.rightBarButtonItem=right;
    self.view.backgroundColor=[UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets=NO;
    [self getMyDetailData];
    
    [self setUpTableView];
    [self setUpBottomBtn];
    [self setUpBgView];
    _DrawTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(updateTimeCountDown) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:_DrawTimer forMode:NSRunLoopCommonModes];
}
#pragma mrak--倒计时
- (void)updateTimeCountDown
{
    _data.RemainderSeconds--;
    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:3] withRowAnimation:UITableViewRowAnimationNone];
}
#pragma mark--分享好友
-(void)shareFriend
{
    _shareView.hidden=NO;
    _bgView.hidden=NO;
}
#pragma mark--底部按钮
-(void)setUpBottomBtn
{
    _bottomBtn=[[UIButton alloc]initWithFrame:CGRectMake(10, kHeight-40-10, kWidth-20, 40)];
    [_bottomBtn setTitle:@"邀请好友参与" forState:UIControlStateNormal];
    [_bottomBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _bottomBtn.layer.cornerRadius=4;
    [_bottomBtn setClipsToBounds:YES];
    _bottomBtn.backgroundColor=BLUECOLOR;
    [_bottomBtn addTarget:self action:@selector(inviteFriend) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_bottomBtn];
}
-(void)setUpBgView
{
    _bgView=[[UIView alloc]initWithFrame:CGRectMake(0, 64, kWidth, kHeight-64)];
    _bgView.backgroundColor=[UIColor blackColor];
    _bgView.alpha=0.7;
    _bgView.hidden=YES;
    [self.view addSubview:_bgView];
    
    _shareView=[[UIView alloc]initWithFrame:CGRectMake(0, kHeight-150, kWidth, 150)];
    _shareView.hidden=YES;
    _shareView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:_shareView];
    
    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(10, 10, 30, 30)];
    [btn setBackgroundImage:[UIImage imageNamed:@"close_view"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(closeView) forControlEvents:UIControlEventTouchUpInside];
    [_shareView addSubview:btn];
    
    UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(btn.frame.origin.x+30, 10, kWidth-10-30, 30)];
    lbl.text=@"拼单邀请链接";
    lbl.textColor=[UIColor darkGrayColor];
    lbl.font=[UIFont systemFontOfSize:15];
    lbl.textAlignment=NSTextAlignmentCenter;
    [_shareView addSubview:lbl];
    
    UIView *line=[[UIView alloc]initWithFrame:CGRectMake(0,41, kWidth, 1)];
    line.backgroundColor=GRAYCOLOR;
    [_shareView addSubview:line];
    
    
    for (int i=0; i<2; i++) {
        UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(i*(50+20)+20, 51, 50, 50)];
        [btn setBackgroundImage:[UIImage imageNamed:@"send_weixin"] forState:UIControlStateNormal];
        btn.tag=(i+1)*200;
        if (i==1) {
             [btn setBackgroundImage:[UIImage imageNamed:@"wxpyq_shar"] forState:UIControlStateNormal];
        }
        [btn addTarget:self action:@selector(share:) forControlEvents:UIControlEventTouchUpInside];
        [_shareView addSubview:btn];
       
    }
}
-(void)share:(UIButton *)btn
{
    _bgView.hidden=YES;
    _shareView.hidden=YES;
    [self getShareMassege];
    if (btn.tag==200) {
        _scene=WXSceneSession;
    }else
    {
        _scene=WXSceneTimeline;
    }
    
    [self share];
}
-(void)closeView
{
   _bgView.hidden=YES;
    _shareView.hidden=YES;
}
-(void)inviteFriend
{
    _bgView.hidden=NO;
    _shareView.hidden=NO;
}
#pragma mark--分享到微信
-(void)share
{
    WXWebpageObject *wxwebobj=[[WXWebpageObject alloc]init];
    wxwebobj.webpageUrl= _shareData.ShareUrl;
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = _shareData.ShareTitle;
    message.description=_shareData.ShareDes;
    NSURL *_url = [NSURL URLWithString: _shareData.ShareImg];// 获取的图片地址
    [message setThumbImage:[UIImage imageWithData: [NSData dataWithContentsOfURL:_url]]];
    message.mediaObject=wxwebobj;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.message = message;
    req.scene = _scene;
    [WXApi sendReq:req];
    
}

#pragma mark--获取要分享的内容
-(void)getShareMassege
{
    //http://192.168.1.107:3722/Common/PageInfo/{UserCode}/{PageType}/{ObjectID}/{Timestamp}/{Sign}
    NSString *timeStamp=[GeneralTool gettimestamp];
    NSDictionary *dic=@{@"UserCode":GETUSERCODE,
                        @"PageType":@"SHARE_URL_SPELL",
                        @"ObjectID":_spellUserId,
                        @"Timestamp":timeStamp};
    NSString *sign=[GeneralTool GetSin:dic];
    NSString *urlString=[NSString stringWithFormat:@"Common/PageInfo/%@/%@/%@/%@/%@",GETUSERCODE,@"SHARE_URL_SPELL",_spellUserId,timeStamp,sign];
    [RequestTool requestDataWithType:@"get" andUrlString:urlString andParameters:nil andRequestFinished:^(id responses, NSError *error) {
        if (error) {
            [MBProgressHUD showError:@"无法获取分享内容，请稍后再试"];
        }
        if([responses[@"IsSuccess"]integerValue]==1)
        {
            _shareData=[[ShareData alloc]initWithDic:responses[@"ReturnObject"]];
            
        }else
        {
            [MBProgressHUD showError:@"无法获取分享内容，请稍后再试"];
        }
        
    }];
    
}

#pragma mark--获取详情数据
-(void)getMyDetailData
{
    //http://192.168.1.107:3722/Activity/MySpellDetail/{UserCode}/{SpellUserID}/{Timestamp}/{Sign}
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString *timeStamp=[GeneralTool gettimestamp];
    NSDictionary *dic=@{@"UserCode":GETUSERCODE,
                        @"SpellUserID":_spellUserId,
                        @"Timestamp":timeStamp,
                        };
    NSString *sign=[GeneralTool GetSin:dic];
    NSString *urlString=[NSString stringWithFormat:@"Activity/MySpellDetail/%@/%@/%@/%@",GETUSERCODE,_spellUserId,timeStamp,sign];
    [RequestTool requestDataWithType:@"get" andUrlString:urlString andParameters:nil andRequestFinished:^(id responses, NSError *error) {
            [MBProgressHUD hideHUDForView:self.view];
            if (error) {
                [MBProgressHUD showError:@"连接服务器失败，请稍后再试"];
            }
            if ([responses[@"IsSuccess"]integerValue]==1)
            {
                _data=[[MyPinDanDetailData alloc]initWithDic:responses[@"ReturnObject"]];
                [_tableView reloadData];
            }else
            {
                [MBProgressHUD showError:@"请求数据失败，请稍后再试"];
            }
    }];
}
#pragma mark--表
-(void)setUpTableView
{
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, kWidth, kHeight-64-70) style:UITableViewStylePlain];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    [_tableView registerNib:[UINib nibWithNibName:@"DetailPinDanCell" bundle:nil] forCellReuseIdentifier:@"section1"];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"section2"];
    [_tableView registerNib:[UINib nibWithNibName:@"MyPinDanDetailSection3Cell" bundle:nil] forCellReuseIdentifier:@"section3"];
    [self.view addSubview:_tableView];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==1 || section==2) {
        return 30;
    }
    return 0;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return 300;
    }else if (indexPath.section==1)
    {
        CGFloat height=[ZMTool getLabelHeight:_data.SpellContent font:[UIFont systemFontOfSize:13] width:kWidth-20];
        return height+20;
    }else if(indexPath.section==2)
    {
        if (_data.HeadImgList.count<=7) {
            return 30+40;
        }else
        {
            int count=21/7.0;
            return (count*30)+((count-1)*10)+40;
       }
    }else
    {
        return 100;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(20, 5, kWidth, 20)];
    lbl.backgroundColor=[UIColor colorWithRed:246/255.0 green:246/255.0  blue:246/255.0  alpha:0.7];
    lbl.font=[UIFont systemFontOfSize:13];
    lbl.textColor=[UIColor lightGrayColor];
    
    if (section==1) {
        lbl.text=@"拼单介绍";
        return lbl;
    }else if(section==2)
    {
        lbl.text=@"参与过的用户";
        return lbl;
    }
    return nil;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        DetailPinDanCell *secrtion1=[_tableView dequeueReusableCellWithIdentifier:@"section1" forIndexPath:indexPath];
        secrtion1.delegate=self.navigationController;
        secrtion1.selectionStyle=UITableViewCellSelectionStyleNone;
        secrtion1.aboutJingJingBtn.layer.cornerRadius=4;
        secrtion1.aboutJingJingBtn.clipsToBounds=YES;
        secrtion1.aboutJingJingBtn.layer.borderColor=BLUECOLOR.CGColor;
        secrtion1.aboutJingJingBtn.layer.borderWidth=1;
        [secrtion1.image sd_setImageWithURL:[NSURL URLWithString:_data.DetailImgUrl] placeholderImage:nil options:SDWebImageRetryFailed];
        secrtion1.title.text=_data.ShareTitle;
        secrtion1.peopleNum.text=[NSString stringWithFormat:@"%ld人",(long)_data.NeedCount];
        secrtion1.require.text=_data.SpellRequire;
        NSArray *Arr=_data.SpellStepList;
        for (NSDictionary *dic in Arr) {
            NSString *step=dic[@"SpellStepID"];
            switch ([step integerValue]) {
                case 1:
                    secrtion1.need1.text=[NSString stringWithFormat:@"①%@",dic[@"SpellStepName"]];
                    secrtion1.need1.textColor=BLUECOLOR;
                    break;
                case 2:
                    secrtion1.need2.text=[NSString stringWithFormat:@"②%@",dic[@"SpellStepName"]];
                    secrtion1.need2.textColor=BLUECOLOR;
                    break;
                case 3:
                    secrtion1.need3.text=[NSString stringWithFormat:@"③%@",dic[@"SpellStepName"]];
                    secrtion1.need3.textColor=[UIColor lightGrayColor];

                    break;
                case 4:
                    secrtion1.need4.text=[NSString stringWithFormat:@"④%@",dic[@"SpellStepName"]];
                    secrtion1.need4.textColor=[UIColor lightGrayColor];

                    break;
                default:
                    break;
            }        }

        return secrtion1;
    }else if (indexPath.section==1)
    {
        UITableViewCell *secrtion2=[_tableView dequeueReusableCellWithIdentifier:@"section2" forIndexPath:indexPath];
        secrtion2.selectionStyle=UITableViewCellSelectionStyleNone;

        CGFloat height=[ZMTool getLabelHeight:_data.SpellContent font:[UIFont systemFontOfSize:13] width:kWidth-20];
        UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(10, 10, kWidth-20, height)];
        lbl.font=[UIFont systemFontOfSize:13];
        lbl.textColor=[UIColor darkGrayColor];
        lbl.text=_data.SpellContent;
        lbl.numberOfLines=0;
        [secrtion2.contentView addSubview:lbl];
        return secrtion2;
    }else if (indexPath.section==2)
    {
        UITableViewCell *secrtion3=[_tableView dequeueReusableCellWithIdentifier:@"section2" forIndexPath:indexPath];
        secrtion3.selectionStyle=UITableViewCellSelectionStyleNone;

        for (int i=0; i<_data.HeadImgList.count; i++) {
            NSDictionary *dic=_data.HeadImgList[i];
            NSString *headImage=dic[@"JoinHeadImg"];
            UIImageView *imageView=[[UIImageView alloc]init];
            [imageView sd_setImageWithURL:[NSURL URLWithString:headImage] placeholderImage:nil options:SDWebImageRetryFailed];
            CGFloat interval=(kWidth-270)/2.0;
            imageView.frame=CGRectMake(i%7*(30+10)+interval, i/7*(30+10)+20, 30, 30);
            [secrtion3.contentView addSubview:imageView];
        }
        return secrtion3;
    }else
    {
        MyPinDanDetailSection3Cell *section4=[_tableView dequeueReusableCellWithIdentifier:@"section3" forIndexPath:indexPath];
        section4.selectionStyle=UITableViewCellSelectionStyleNone;

        NSInteger interval = labs(_data.RemainderSeconds);
        NSInteger hours = ((NSInteger)interval)%(3600*24)/3600;
        NSInteger minutes = ((NSInteger)interval)%(3600*24)%3600/60;
        NSInteger seconds = ((NSInteger)interval)%(3600*24)%3600%60;
        if (_data.RemainderSeconds<=0)
        {
            [_DrawTimer fire];
            _DrawTimer=nil;
            
        }else
        {
            section4.hour1.text=[NSString stringWithFormat:@"%ld",hours/10];
            section4.hour2.text=[NSString stringWithFormat:@"%ld",hours%10];
            section4.minute1.text=[NSString stringWithFormat:@"%ld",minutes/10];
            section4.minute2.text=[NSString stringWithFormat:@"%ld",minutes%10];
            section4.second1.text=[NSString stringWithFormat:@"%ld",seconds/10];
            section4.second2.text=[NSString stringWithFormat:@"%ld",seconds%10];
        }

        return section4;
    }
}
#pragma mark--进入进出
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [GeneralTool hideTabBar];
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [GeneralTool showTabBar];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    _bgView.hidden=YES;
    _shareView.hidden=YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
